package ocean.chinacraft.common.world.entity.ai.goal;

import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.goal.target.TargetGoal;
import net.minecraft.world.entity.ai.targeting.TargetingConditions;
import net.minecraft.world.entity.player.Player;
import ocean.chinacraft.common.config.ApplicationConfig;
import ocean.chinacraft.common.util.ModUtil;
import ocean.chinacraft.common.world.item.armor.SilkNightArmor;

import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义目标
 *
 * @author zhang
 * @since 2021/12/13
 */
public class ModAttackGoal extends TargetGoal {


    private static final Predicate<LivingEntity> LIVING_ENTITY_SELECTOR =
            LivingEntity::attackable;

    private static final TargetingConditions TARGETING_CONDITIONS =
            TargetingConditions.forCombat().range(20.0D).selector(LIVING_ENTITY_SELECTOR);


    public ModAttackGoal(Mob entity, boolean mustSee) {
        super(entity, mustSee);
    }

    @Override
    public boolean canUse() {
        return true;
    }

    @Override
    public void tick() {
        LivingEntity target = mob.getTarget();
        if (target instanceof Player player) {
            if (SilkNightArmor.invalid(player)) {
                List<Mob> mobEntities = ModUtil.getNearbyMobs(player, 20, TARGETING_CONDITIONS);
                for (Mob mob : mobEntities) {
                    if (ApplicationConfig.NIGHT_ARMOR_SWITCH.get()) {
                        if (mob.getLastAttacker() != null && mob.getLastAttacker().isAlive() && mob.getLastAttacker().getUUID().equals(player.getUUID())) {
                            break;
                        }
                    }
                    if (mob.getTarget() != null && mob.getTarget().getUUID().equals(player.getUUID())) {
                        mob.setTarget(null);
                    }
                }
            }
        }
    }
}
